﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Collections.Generic;
using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.Model.Enum;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;

namespace HZ.DrugTrade.Web.Hospitals.StorageManage
{
    public partial class StorageGoodsList : BasePage
    {
        public StorageGoodsList()
        {
            this.ModuleNo = Module.入库单管理.ToString();
            this.PageOperateType = OperateType.入库.ToString();

        }
        private int totalRecord;
        private IList<HZ.DrugTrade.Model.View.Distribution> PurchaseOrderDetailList;
        private IList<PurchaseOrderDetail> aPurchaseOrderDetailList = new List<PurchaseOrderDetail>();
        private IList<HZ.DrugTrade.Model.View.Distribution> aDistributionList = new List<HZ.DrugTrade.Model.View.Distribution>();
        private IBLL_Purchase iPurchase = Factory.BLL_Purchase();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!HZ.DrugTrade.Web.Function.IsThreeLevel())//项目查询条件仅三级医院可见
            {
                this.ddlProjectid.Visible = false;
                this.lblProjectid.Visible = false;
            }
            if (!IsPostBack)
            {
                Binddata();
            }

        }

        protected void btnFinish_Click(object sender, EventArgs e)
        {
            Save();
        }
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            Binddata();
        }
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            Binddata();
        }

        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                txtAddTimeFromPS.Text = "";
                txtAddTimeToPS.Text = "";
                txtCompanyName_PS.Text = "";
                txtCompanyName_SC.Text = "";
                //txtPinyinCode.Text = "";
            }
        }

        /// <summary>
        /// 页面修改，只显示未入库列表，去除入库状态查询
        /// </summary>
        protected void Binddata()
        {

            Model.Query.Distribution qryCondition = new HZ.DrugTrade.Model.Query.Distribution();
            qryCondition.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            qryCondition.OrderDetailState = 2;
            qryCondition.DistributeState = 0;
            qryCondition.GoodsName = txtGoodsName.Text.Trim();
            qryCondition.CompanyName_PS = txtCompanyName_PS.Text.Trim();
            qryCondition.CompanyName_SC = txtCompanyName_SC.Text.Trim();
            //qryCondition.PinyinCode = txtPinyinCode.Text.Trim();
            qryCondition.Material = txtMaterial.Text.Trim();
            //qryCondition.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                qryCondition.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                qryCondition.ProjectID = "0001";
            }
            qryCondition.Outlookc = txtOutLook.Text.Trim();
            qryCondition.DistributeTimeFrom = new HZ.Common.ConvertHelper(txtAddTimeFromPS.Text.Trim()).ToDateTime;
            qryCondition.DistributeTimeTo = new HZ.Common.ConvertHelper(txtAddTimeToPS.Text.Trim()).ToDateTime;
            qryCondition.SortFields = " DistributeTime desc,OrderName ASC ,goodsid";

            PurchaseOrderDetailList = iPurchase.GetPurchaseOrderDetail_DistributeByWhere(qryCondition, this.AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalRecord);

            this.gvwProduceCatalog.AutoGenerateColumns = false;
            gvwProduceCatalog.DataSource = PurchaseOrderDetailList;
            gvwProduceCatalog.DataBind();
            this.AspNetPager1.RecordCount = totalRecord;

            //隐藏不需要的列
            //gvwProduceCatalog.Columns[4].Visible = false;

        }

        protected void Save()
        {
            try
            {
                for (int i = 0; i < gvwProduceCatalog.Rows.Count; i++)
                {
                    System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                    TextBox txtPurchaseCount = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtCount");
                    Label lblOrderDetailID = (Label)gvwProduceCatalog.Rows[i].FindControl("OrderDetailID");
                    Label lblDistributeCount = (Label)gvwProduceCatalog.Rows[i].FindControl("lblDistributeCount");
                    TextBox txtBatchRecordID = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtBatchRecordID");
                    if (chk.Checked == true)
                    {
                        //采购数量不能为空
                        if (string.IsNullOrEmpty(txtPurchaseCount.Text.Trim()))
                        {
                            HZ.Web.WebUtil.Alert("入库数量不能为空！", this);
                            txtPurchaseCount.Focus();
                            return;
                        }
                        //入库数量不能大于批配送量
                        if (!string.IsNullOrEmpty(lblDistributeCount.Text.Trim()))
                        {
                            if (Convert.ToInt32(txtPurchaseCount.Text.Trim()) > Convert.ToInt32(lblDistributeCount.Text))
                            {
                                HZ.Web.WebUtil.Alert("入库数量不能大于批配送量！", this);
                                txtPurchaseCount.Focus();
                                return;
                            }
                            else if (Convert.ToInt32(txtPurchaseCount.Text.Trim()) <= 0)
                            {
                                HZ.Web.WebUtil.Alert("入库数量必须大于0", this);
                                txtPurchaseCount.Focus();
                                return;
                            }
                        }


                        Model.View.Distribution aDistribution = new Model.View.Distribution();//实体层
                        //aDistribution.WarehouseCount = new HZ.Common.ConvertHelper(txtPurchaseCount.Text).ToInt32;
                        aDistribution.DistributionSerialID = new HZ.Common.ConvertHelper(chk.Value).String;
                        aDistribution.OrderDetailID = new HZ.Common.ConvertHelper(lblOrderDetailID.Text).String; //gvwProduceCatalog.Rows[i].Cells[14].Text.ToString();
                        //获取实时的数据 add by zdc 防止在入库的一瞬间配送企业有更新配送量的情况
                        object obj = HZ.Data.DbHelperFactory.Create().ExecuteScalar("select DistributeCount from tb_distribution where DistributionSerialID='" + aDistribution.DistributionSerialID + "'");
                        if (obj != null)
                        {
                            //判断确认入库的瞬间配送企业是否更新过配送量，若有更新，则阻止 add by ysm 20130201
                            if (Convert.ToInt32(lblDistributeCount.Text) != new HZ.Common.ConvertHelper(obj.ToString()).ToInt32)
                            {
                                HZ.Web.WebUtil.Alert("配送企业已更新配送量，请刷新后重新操作！", this);
                                return;
                            }
                            else
                            {
                                aDistribution.WarehouseCount = Convert.ToInt32(txtPurchaseCount.Text.Trim());
                            }
                        }
                        else //没有查询到配送量，阻止操作 add by ysm 20130201
                        {
                            HZ.Web.WebUtil.Alert("未查到记录！", this);
                            return;
                        }

                        //add by hw
                        string ProcureCatalogID = gvwProduceCatalog.DataKeys[i][0].ToString();
                        string CompanyPsID = gvwProduceCatalog.DataKeys[i][1].ToString();
                        string CompanyName_PS = gvwProduceCatalog.DataKeys[i][2].ToString();
                        aDistribution.ProcureCatalogID = ProcureCatalogID;
                        aDistribution.CompanyID_PS = CompanyPsID;
                        aDistribution.CompanyName_PS = CompanyName_PS;


                        aDistributionList.Add(aDistribution);
                    }
                }
                int nSuccess = iPurchase.UpdatePurchaseOrderDetail_Warehouse_Batch2(aDistributionList, CurrentAccount.GetUser().Org.OrgID, CurrentAccount.GetUser().Org.OrgName, CurrentAccount.GetUser().Org.Area.AreaID);
                if (nSuccess == 1)
                {
                    HZ.Web.WebUtil.Alert("入库成功！", this);
                    Binddata();
                }
                else
                {
                    HZ.Web.WebUtil.Alert("入库失败！", this);

                }
            }
            catch (System.Exception ex)
            {
                HZ.Web.WebUtil.Alert("入库异常！" + ex.Message.ToString(), this);
            }

        }

        protected void gvwProduceCatalog_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

            }


        }
        /// <summary>
        /// 全部确认入库2009-11-14
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAll_Click(object sender, EventArgs e)
        {
            try
            {
                #region
                //Model.Query.Distribution qryCondition = new HZ.DrugTrade.Model.Query.Distribution();
                //qryCondition.HospitalID = CurrentAccount.GetUser().Org.OrgID;
                //qryCondition.GoodsName = txtGoodsName.Text.Trim();
                //qryCondition.CompanyName_PS = txtCompanyName_PS.Text.Trim();
                //qryCondition.CompanyName_SC = txtCompanyName_SC.Text.Trim();
                //qryCondition.PinyinCode = txtPinyinCode.Text.Trim();
                //qryCondition.Material = txtMaterial.Text.Trim();
                //qryCondition.Outlookc = txtOutLook.Text.Trim();
                //qryCondition.DistributeTimeFrom = new HZ.Common.ConvertHelper(txtAddTimeFromPS.Text.Trim()).ToDateTime;
                //qryCondition.DistributeTimeTo = new HZ.Common.ConvertHelper(txtAddTimeToPS.Text.Trim()).ToDateTime;
                //qryCondition.SortFields = " DistributeTime desc,OrderName ASC ,goodsid";
                //int totalRecord = 0;
                //PurchaseOrderDetailList = iPurchase.GetPurchaseOrderDetail_DistributeByWhere(qryCondition, 1, 0, out totalRecord);
                //foreach (var item in PurchaseOrderDetailList)
                //{
                //    Model.View.Distribution aDistribution = new Model.View.Distribution();
                //    aDistribution.OrderDetailID = item.OrderDetailID;//全部确认时，入库数量和配送数量默认相等
                //    aDistribution.WarehouseCount = item.Dis_DistributeCount;
                //    aDistribution.DistributionSerialID = item.DistributionSerialID;

                //    aDistribution.ProcureCatalogID = item.ProcureCatalogID;
                //    aDistribution.CompanyID_PS = item.CompanyID_PS;
                //    aDistribution.CompanyName_PS = item.CompanyName_PS;

                //    aDistributionList.Add(aDistribution);
                //}
                #endregion
                for (int i = 0; i < gvwProduceCatalog.Rows.Count; i++)
                {
                    System.Web.UI.HtmlControls.HtmlInputCheckBox chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)gvwProduceCatalog.Rows[i].FindControl("checkbox1");
                    TextBox txtPurchaseCount = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtCount");
                    Label lblOrderDetailID = (Label)gvwProduceCatalog.Rows[i].FindControl("OrderDetailID");
                    Label lblDistributeCount = (Label)gvwProduceCatalog.Rows[i].FindControl("lblDistributeCount");
                    TextBox txtBatchRecordID = (TextBox)gvwProduceCatalog.Rows[i].FindControl("txtBatchRecordID");
                    //采购数量不能为空
                    if (string.IsNullOrEmpty(txtPurchaseCount.Text.Trim()))
                    {
                        HZ.Web.WebUtil.Alert("入库数量不能为空！", this);
                        txtPurchaseCount.Focus();
                        return;
                    }
                    //入库数量不能大于批配送量
                    if (!string.IsNullOrEmpty(lblDistributeCount.Text.Trim()))
                    {
                        if (Convert.ToInt32(txtPurchaseCount.Text.Trim()) > Convert.ToInt32(lblDistributeCount.Text))
                        {
                            HZ.Web.WebUtil.Alert("入库数量不能大于批配送量！", this);
                            txtPurchaseCount.Focus();
                            return;
                        }
                        else if (Convert.ToInt32(txtPurchaseCount.Text.Trim()) <= 0)
                        {
                            HZ.Web.WebUtil.Alert("入库数量必须大于0", this);
                            txtPurchaseCount.Focus();
                            return;
                        }
                    }


                    Model.View.Distribution aDistribution = new Model.View.Distribution();//实体层
                    //aDistribution.WarehouseCount = new HZ.Common.ConvertHelper(txtPurchaseCount.Text).ToInt32;
                    aDistribution.DistributionSerialID = new HZ.Common.ConvertHelper(chk.Value).String;
                    aDistribution.OrderDetailID = new HZ.Common.ConvertHelper(lblOrderDetailID.Text).String; //gvwProduceCatalog.Rows[i].Cells[14].Text.ToString();
                    //获取实时的数据 add by zdc 防止在入库的一瞬间配送企业有更新配送量的情况
                    object obj = HZ.Data.DbHelperFactory.Create().ExecuteScalar("select DistributeCount from tb_distribution where DistributionSerialID='" + aDistribution.DistributionSerialID + "'");
                    if (obj != null)
                    {
                        //判断确认入库的瞬间配送企业是否更新过配送量，若有更新，则阻止 add by ysm 20130201
                        if (Convert.ToInt32(lblDistributeCount.Text) != new HZ.Common.ConvertHelper(obj.ToString()).ToInt32)
                        {
                            HZ.Web.WebUtil.Alert("配送企业已更新配送量，请刷新后重新操作！", this);
                            return;
                        }
                        else
                        {
                            aDistribution.WarehouseCount = Convert.ToInt32(txtPurchaseCount.Text.Trim());
                        }
                    }
                    else //没有查询到配送量，阻止操作 add by ysm 20130201
                    {
                        HZ.Web.WebUtil.Alert("未查到记录！", this);
                        return;
                    }

                    //add by hw
                    string ProcureCatalogID = gvwProduceCatalog.DataKeys[i][0].ToString();
                    string CompanyPsID = gvwProduceCatalog.DataKeys[i][1].ToString();
                    string CompanyName_PS = gvwProduceCatalog.DataKeys[i][2].ToString();
                    aDistribution.ProcureCatalogID = ProcureCatalogID;
                    aDistribution.CompanyID_PS = CompanyPsID;
                    aDistribution.CompanyName_PS = CompanyName_PS;


                    aDistributionList.Add(aDistribution);
                }
                int nSuccess = iPurchase.UpdatePurchaseOrderDetail_Warehouse_Batch2(aDistributionList, CurrentAccount.GetUser().Org.OrgID, CurrentAccount.GetUser().Org.OrgName, CurrentAccount.GetUser().Org.Area.AreaID);
                if (nSuccess == 1)
                {
                    HZ.Web.WebUtil.Alert("入库成功！", this);
                    Binddata();
                }
                else
                {
                    HZ.Web.WebUtil.Alert("入库失败！", this);

                }
            }
            catch (System.Exception ex)
            {
                HZ.Web.WebUtil.Alert("入库异常！" + ex.Message.ToString(), this);
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Model.Query.Distribution qryCondition = new HZ.DrugTrade.Model.Query.Distribution();
            qryCondition.HospitalID = CurrentAccount.GetUser().Org.OrgID;
            qryCondition.OrderDetailState = 2;
            qryCondition.DistributeState = 0;
            qryCondition.GoodsName = txtGoodsName.Text.Trim();
            qryCondition.CompanyName_PS = txtCompanyName_PS.Text.Trim();
            qryCondition.CompanyName_SC = txtCompanyName_SC.Text.Trim();
            //qryCondition.PinyinCode = txtPinyinCode.Text.Trim();
            qryCondition.PinyinCode = this.txtpinyincode.Text.Trim();
            qryCondition.Material = txtMaterial.Text.Trim();
            qryCondition.Outlookc = txtOutLook.Text.Trim();
            //qryCondition.ProjectID = this.ddlProjectid.SelectedValue;
            if (this.ddlProjectid.Visible != false)
            {
                qryCondition.ProjectID = this.ddlProjectid.SelectedValue;
            }
            else
            {
                qryCondition.ProjectID = "0001";
            }
            qryCondition.DistributeTimeFrom = new HZ.Common.ConvertHelper(txtAddTimeFromPS.Text.Trim()).ToDateTime;
            qryCondition.DistributeTimeTo = new HZ.Common.ConvertHelper(txtAddTimeToPS.Text.Trim()).ToDateTime;
            qryCondition.SortFields = " DistributeTime desc,OrderName ASC ,goodsid";
            string where = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition<HZ.DrugTrade.Model.Query.Distribution>(qryCondition, true);
            string sql = string.Format(@"SELECT Goodsid 产品编号,Dis_DistributeCount 入库量,Dis_WarehouseCount 已入库,Dis_DistributeCount 批配送量,Price 采购价,
                                    GoodsName 产品名称,Outlookc 规格型号,Material 材质, Unit 最小计量单位,QualityLevel 产品类别,ProcurePrice 采购限价, CompanyName_SC 生产企业,
                        CompanyName_PS 配送企业,OrderName 采购单,BatchRecordID 批号,DistributeTime 配送时间 FROM View_Distribution WHERE 1=1 {0}", where);
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "验收入库.xls");
        }
    }
}
